import * as React from 'react'
import { IconChevron } from 'components/icon/chevron'
import { ChallengeContents } from './challenges'
import { debounce } from 'debounce'
import tw from 'twin.macro'

export function Navigation({
  challenges,
  handleChange,
  currentChallenge,
  isRecipes,
}: {
  challenges: ChallengeContents[]
  handleChange: (index: number) => void
  currentChallenge: ChallengeContents
  isRecipes?: boolean
}) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const challengesNavRef = React.useRef(challenges.map(() => React.createRef<HTMLButtonElement>()))
  const scrollPos = currentChallenge.order - 1
  const canScrollLeft = scrollPos > 0
  const canScrollRight = scrollPos < challenges.length - 1

  const handleScrollRight = () => {
    if (scrollPos < challenges.length - 1) {
      const currentNavRef = challengesNavRef.current[scrollPos + 1].current
      if (!currentNavRef) {
        return
      }
      if (containerRef.current) {
        containerRef.current.scrollLeft = currentNavRef.offsetLeft
      }
      handleChange(scrollPos + 1)
    }
  }

  const handleScrollLeft = () => {
    if (scrollPos > 0) {
      const currentNavRef = challengesNavRef.current[scrollPos - 1].current
      if (!currentNavRef) {
        return
      }
      if (containerRef.current) {
        containerRef.current.scrollLeft = currentNavRef.offsetLeft
      }
      handleChange(scrollPos - 1)
    }
  }

  const handleSelectNav = (index: number) => {
    const currentNavRef = challengesNavRef.current[index].current
    if (containerRef.current) {
      containerRef.current.scrollLeft = currentNavRef?.offsetLeft || 0
    }
    handleChange(index)
  }

  const handleResize = React.useCallback(() => {
    if (containerRef.current) {
      const el = containerRef.current
      el.scrollLeft = challengesNavRef.current[scrollPos].current?.offsetLeft || 0
    }
  }, [containerRef, challengesNavRef, scrollPos])

  React.useEffect(() => {
    handleResize()
    const debouncedHandleResize = debounce(handleResize, 200)
    window.addEventListener('resize', debouncedHandleResize)
    return () => {
      window.removeEventListener('resize', debouncedHandleResize)
    }
  }, [handleResize])

  return (
    <div tw="flex items-center justify-between">
      <div tw="overflow-hidden">
        <div ref={containerRef} tw="box-content relative flex overflow-x-auto transition-transform">
          {challenges.map(({ name, id, order }, index) => (
            <button
              css={[
                tw`mr-4 text-ellipsis whitespace-nowrap border-b-4 py-2 text-base transition duration-100 ease-in`,
                isRecipes &&
                  currentChallenge.id === id &&
                  tw`dark:text-purple-30 dark:border-purple-30 dark:hover:text-purple-30 border-purple-50 text-purple-50 hover:text-purple-50`,
                !isRecipes &&
                  currentChallenge.id === id &&
                  tw`text-link border-link hover:text-link dark:text-link-dark dark:border-link-dark dark:hover:text-link-dark`,
              ]}
              onClick={() => handleSelectNav(index)}
              key={`button-${id}`}
              ref={challengesNavRef.current[index]}
            >
              {order}. {name}
            </button>
          ))}
        </div>
      </div>
      <div tw="z-10 flex pb-2 pl-2">
        <button
          onClick={handleScrollLeft}
          aria-label="Scroll left"
          css={[
            tw`bg-secondary-button dark:bg-secondary-button-dark border-gray-20 h-8 rounded-l border-r px-2`,
            canScrollLeft && tw`dark:text-primary-dark text-primary`,
            !canScrollLeft && tw`text-gray-30`,
          ]}
        >
          <IconChevron displayDirection="left" />
        </button>
        <button
          onClick={handleScrollRight}
          aria-label="Scroll right"
          css={[
            tw`bg-secondary-button dark:bg-secondary-button-dark h-8 rounded-r px-2`,
            canScrollRight && tw`dark:text-primary-dark text-primary`,
            !canScrollRight && tw`text-gray-30`,
          ]}
        >
          <IconChevron displayDirection="right" />
        </button>
      </div>
    </div>
  )
}
